package cn.com.lms.business.questionnaire.web;

import cn.com.lms.business.core.constant.ErrorEnum;
import cn.com.lms.business.core.util.SystemUserUtil;
import cn.com.lms.business.learning.service.LearningPlanService;
import cn.com.lms.business.questionnaire.persistence.entity.QuestionnaireInfo;
import cn.com.lms.business.questionnaire.service.QuestionnaireInfoService;
import cn.com.lms.business.user.persistence.entity.SysUserVo;

import com.bnzj.core.exception.BusinessException;
import com.bnzj.core.persistence.query.CompareExpression;
import com.bnzj.core.persistence.query.CompareType;
import com.bnzj.core.persistence.query.IExpression;

import com.bnzj.core.persistence.query.QueryHelpBean;
import com.bnzj.core.persistence.util.EntityUtils;
import com.bnzj.core.rest.ResponseResult;

import com.bnzj.core.util.BeanUtils;
import com.bnzj.core.webmvc.util.WebMvcUtils;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.media.Content;
import io.swagger.v3.oas.annotations.media.Schema;
import io.swagger.v3.oas.annotations.responses.ApiResponse;
import io.swagger.v3.oas.annotations.tags.Tag;
import org.apache.commons.lang3.ObjectUtils;
import org.jetbrains.annotations.NotNull;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.Date;
import java.util.List;
import java.util.Optional;

import static cn.com.lms.business.constant.LmsConstant.ASCEND;
import static cn.com.lms.business.constant.LmsConstant.DESCEND;

/**
 * @Author: 16266
 * @DateTime: 2020/3/20 14:14
 * @Description: 调查问卷web层
 */
@Tag(name = "问卷调查", description = "问卷调查列表")
@RestController
@RequestMapping(value = "/questionnaire")
public class QuestionnaireInfoController {

    @Autowired
    private QuestionnaireInfoService questionnaireInfoService;
    @Autowired
    private LearningPlanService planService;

    @Operation(summary = "问卷新增", responses = {
            @ApiResponse(responseCode = "1", description = "新增成功", content = @Content(mediaType = "application/json", schema = @Schema(implementation = ResponseResult.class))),
            @ApiResponse(responseCode = "0", description = "新增失败")})
    @PostMapping(value = "/add")
    public ResponseResult<QuestionnaireInfo> addQuestionnaireInfo(@RequestBody QuestionnaireInfo questionnaireInfo) {
        SysUserVo currentUser = SystemUserUtil.getCurrentUser();
        EntityUtils.saveBefore(questionnaireInfo, currentUser.getAccount(), currentUser.getCname());
        questionnaireInfo.setIsDelete(false);
        questionnaireInfo.setStatus((byte) 0);
        questionnaireInfoService.save(questionnaireInfo);
        return ResponseResult.success();
    }

    @Operation(summary = "分页查询问卷", description = "", parameters = {
            @Parameter(name = "offset", description = "起始页", schema = @Schema(name = "offset", description = "", implementation = String.class)),
            @Parameter(name = "limit", description = "页大小", schema = @Schema(name = "limit", description = "", implementation = String.class)),
            @Parameter(name = "keyWord", description = "目录名称进行模糊搜索", schema = @Schema(name = "keyWord", description = "", implementation = String.class)),
            @Parameter(name = "status", description = "按状态查询", schema = @Schema(name = "status", description = "", implementation = Byte.class)),
            @Parameter(name = "timeSort", description = "时间排序", schema = @Schema(name = "timeSort", description = "", implementation = String.class))
    })
    @GetMapping(value = "/page")
    public ResponseResult<Page<QuestionnaireInfo>> getQuestionnaireInfo(HttpServletRequest request) {
        Pageable pageable = null;
        //判断参数排序
        if (ASCEND.equals(request.getParameter("timeSort"))) {
            pageable = WebMvcUtils.initPage(request, Sort.by(Sort.Direction.ASC, "create_time"));
        } else if (DESCEND.equals(request.getParameter("timeSort"))) {
            pageable = WebMvcUtils.initPage(request, Sort.by(Sort.Direction.DESC, "create_time"));
        } else {
            pageable = WebMvcUtils.initPage(request, Sort.by(Sort.Direction.DESC, "create_time"));
        }
        QueryHelpBean dicQueryBean = questionnaireInfoService.getQueryHelpBean();
        dicQueryBean.setPageable(pageable);
        //根据状态查询
        IExpression orCondition = CompareExpression.build("d.status", CompareType.equal, request.getParameter("status"));
        //问卷查询未删除
        IExpression orCondition1 = CompareExpression.build("d.is_delete", CompareType.equal, false);
        //问卷名称模糊搜索
        IExpression orCondition2 = CompareExpression.build("d.questionnaire_name", CompareType.like, request.getParameter("keyWord"));
        dicQueryBean.addWhere(orCondition.and(orCondition1.and(orCondition2)));
        Page<QuestionnaireInfo> page = questionnaireInfoService.findAll(dicQueryBean);
        return ResponseResult.success(page);
    }

    @Operation(summary = "问卷详情", parameters = {@Parameter(name = "planId", description = "计划ID")})
    @GetMapping(value = "/find/{id}")
    public ResponseResult<QuestionnaireInfo> findQuestionnaireInfoById(HttpServletRequest request, @PathVariable Long id) {
        //记录学员已参加过计划记录
        if (null != request.getParameter("planId")) {
            planService.addPlanJoinRecord(Long.valueOf(request.getParameter("planId")));
        }
        QuestionnaireInfo questionnaireInfo = questionnaireInfoService.findByIdAndIsDeleteEqual(id, false);
        return ResponseResult.success(questionnaireInfo);
    }

    @Operation(summary = "更新", responses = {
            @ApiResponse(responseCode = "1", description = "更新成功", content = @Content(mediaType = "application/json", schema = @Schema(implementation = ResponseResult.class))),
            @ApiResponse(responseCode = "0", description = "更新失败")})
    @PostMapping("/update")
    public ResponseResult<?> updateCatalogManage(@RequestBody QuestionnaireInfo questionnaireInfo) {
        getObject(questionnaireInfo);
        return getResponseResult(questionnaireInfo);
    }

    @Operation(summary = "删除，批量删除", description = "根据分类id删除试题")
    @PostMapping("/delete")
    public ResponseResult<Integer> deleteById(@RequestBody List<Long> id) {
        Integer count = questionnaireInfoService.updateIsDelete(true, id);
        return ResponseResult.success(count);

    }

    /**
     * 更新删除设置日期逻辑
     *
     * @param questionnaireInfo
     */
    private void getObject(@RequestBody QuestionnaireInfo questionnaireInfo) {
        if (ObjectUtils.isEmpty(questionnaireInfo.getId())) {
            throw new BusinessException(ErrorEnum.RECORD_NOT_EXIST.getMessage(), "" + ErrorEnum.RECORD_NOT_EXIST.getCode());
        }
        SysUserVo currentUser = SystemUserUtil.getCurrentUser();
        questionnaireInfo.setModifyBy(currentUser.getCname());
        questionnaireInfo.setModifyName(currentUser.getModifyName());
        questionnaireInfo.setModifyTime(new Date());
    }

    /**
     * 复制对象后更新数据
     *
     * @param questionnaireInfo
     * @return
     */
    @NotNull
    private ResponseResult<?> getResponseResult(@RequestBody QuestionnaireInfo questionnaireInfo) {
        Optional<QuestionnaireInfo> questionnaireInfoOpt = questionnaireInfoService.findById(questionnaireInfo.getId());
        if (!questionnaireInfoOpt.isPresent()) {
            throw new BusinessException(ErrorEnum.RECORD_NOT_EXIST.getMessage(), "" + ErrorEnum.RECORD_NOT_EXIST.getCode());
        }
        QuestionnaireInfo questionnaireInfoDb = questionnaireInfoOpt.get();
        BeanUtils.copyProperties(questionnaireInfo, questionnaireInfoDb);
        questionnaireInfoService.save(questionnaireInfoDb);
        return ResponseResult.success();
    }


}
